package org.dromara.kitchen.controller;

import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.mybatis.core.page.PageUtils;
import org.dromara.kitchen.domain.coupon.KitchenCoupon;
import org.dromara.kitchen.service.IBdProvinceService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.kitchen.domain.Agent;
import org.dromara.kitchen.service.IAgentService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 代理
 *
 * @author Mr.Zhou
 * @date 2024-12-06
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/kitchen/agent")
public class AgentController extends BaseController {

    private final IAgentService agentService;
    private final IBdProvinceService bdProvinceService;

    /**
     * 查询代理列表
     */
    @SaCheckPermission("kitchen:agent:list")
    @GetMapping("/list")
    public TableDataInfo<Agent> list(Agent agent, PageQuery pageQuery) {
        QueryWrapper<Agent> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(agent.getAgentName())){
            qw.like("agent_name", agent.getAgentName());
        }
        qw.orderByDesc("id");

        TableDataInfo<Agent> td = PageUtils.buildDataInfo(agentService.page(PageUtils.buildPage(),qw));
        List<Agent> list = td.getRows();
        for (Agent agent1 : list){
            agent1.setAreaName(bdProvinceService.getAreaNameByAreaId(agent1.getProvId(), agent1.getCityId(), agent1.getDistrictId()));
        }
        return td;
    }

    /**
     * 导出代理列表
     */
    @SaCheckPermission("kitchen:agent:export")
    @Log(title = "代理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(Agent agent, HttpServletResponse response) {
        List<Agent> list = agentService.list();
        ExcelUtil.exportExcel(list, "代理", Agent.class, response);
    }

    /**
     * 获取代理详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("kitchen:agent:query")
    @GetMapping("/{id}")
    public R<Agent> getInfo(@NotNull(message = "主键不能为空") @PathVariable Integer id) {
        Agent agent = agentService.getById(id);
        if(agent!= null){
            if(agent.getProvId() != null){
                String[] areas = { agent.getProvId() + ""};
                agent.setProvinceArray(areas);
            }

            if(agent.getProvId() != null && agent.getCityId() != null){
                String[] areas = { agent.getProvId() + "", agent.getCityId() + ""};
                agent.setProvinceArray(areas);
            }

            if(agent.getProvId() != null && agent.getCityId() != null && agent.getDistrictId() != null){
                String[] areas = { agent.getProvId() + "", agent.getCityId() + "", agent.getDistrictId() + ""};
                agent.setProvinceArray(areas);
            }
        }
        return R.ok(agent);
    }

    /**
     * 新增代理
     */
    @SaCheckPermission("kitchen:agent:add")
    @Log(title = "代理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody Agent agent) {
        if(agent.getProvinceArray()!=null && agent.getProvinceArray().length >= 2){
            agent.setProvId(Integer.parseInt(agent.getProvinceArray()[0]));
            agent.setCityId(Integer.parseInt(agent.getProvinceArray()[1]));
        }

        if(agent.getProvinceArray()!=null && agent.getProvinceArray().length > 2) {
            agent.setDistrictId(Integer.parseInt(agent.getProvinceArray()[2]));
        }
        return toAjax(agentService.save(agent));
    }

    /**
     * 修改代理
     */
    @SaCheckPermission("kitchen:agent:edit")
    @Log(title = "代理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody Agent agent) {

        if(agent.getProvinceArray()!=null && agent.getProvinceArray().length >= 2){
            agent.setProvId(Integer.parseInt(agent.getProvinceArray()[0]));
            agent.setCityId(Integer.parseInt(agent.getProvinceArray()[1]));
        }
        if(agent.getProvinceArray()!=null && agent.getProvinceArray().length > 2) {
            agent.setDistrictId(Integer.parseInt(agent.getProvinceArray()[2]));
        }
        return toAjax(agentService.updateById(agent));
    }

    /**
     * 删除代理
     *
     * @param ids 主键串
     */
    @SaCheckPermission("kitchen:agent:remove")
    @Log(title = "代理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
        return toAjax(agentService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
